<?php
/*****************************************************************************
 **                                                                         ** 
 **                                         .o.                   o8o  	    **
 **                                        .888.                  `"'  	    **
 **     ooo. .oo.  .oo.   oooo    ooo     .8"888.     oo.ooooo.  oooo  	    **
 **     `888P"Y88bP"Y88b   `88.  .8'     .8' `888.     888' `88b `888  	    **
 **      888   888   888    `88..8'     .88ooo8888.    888   888  888  	    **
 **      888   888   888     `888'     .8'     `888.   888   888  888  	    **
 **     o888o o888o o888o     .8'     o88o     o8888o  888bod8P' o888o      **
 **                       .o..P'                       888             	    **
 **                       `Y8P'                       o888o            	    **
 **                                                                         **
 **                                                                         **
 **   Joomla! 1.5 Module myApi_fblogin                                      **
 **   @Copyright Copyright (C) 2010 - Thomas Welton                         **
 **   @license GNU/GPL http://www.gnu.org/copyleft/gpl.html                 **	
 **                                                                         **	
 **   myApi_fblogin is free software: you can redistribute it and/or modify **
 **   it under the terms of the GNU General Public License as published by  **
 **   the Free Software Foundation, either version 3 of the License, or	    **	
 **   (at your option) any later version.                                   **
 **                                                                         **
 **   myApi_fblogin is distributed in the hope that it will be useful,	    **
 **   but WITHOUT ANY WARRANTY; without even the implied warranty of	    **
 **   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         **
 **   GNU General Public License for more details.                          **
 **                                                                         **
 **   You should have received a copy of the GNU General Public License	    **
 **   along with myApi_fblogin.  If not, see <http://www.gnu.org/licenses/> **
 **                                                                         **			
 *****************************************************************************/
 
//don't allow other scripts to grab and execute our file
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
if(!file_exists(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_myapi'.DS.'helpers'.DS.'facebook.php')){ return; }

$doc =& JFactory::getDocument();
$doc->addStyleSheet('modules/mod_myapi_fbLogin/fbLogin.css');
$redirect_logout = JURI::base();


$userRedirect = $params->get('login_userRedirect');
$button_size = $params->get('login_size');
if($userRedirect == '0')
{
	//same page
	$u =& JFactory::getURI(); 
	$redirect_login = JRoute::_($u->toString(),false);
}
else
{
	//redirect to different page
	$menuitem = $params->get('login_userRedirectTo');
	$redirect_login = JRoute::_(JFactory::getApplication()->getMenu()->getItem( $menuitem )->link . "&Itemid=".$menuitem,false);
		
}
$redirect_login = $redirect_login;

$user = JFactory::getUser();
global $facebook;

require_once JPATH_ADMINISTRATOR.DS.'components'.DS.'com_myapi'.DS.'models'.DS.'facebook.php';
$facebookmodel = new myapiModelfacebook;  //Bring the myAPI facebook model

$linked = false;
$user = JFactory::getUser();
if(!$user->guest){
	
  $db = JFactory::getDBO();
  $query = "SELECT * FROM ".$db->nameQuote('#__myapi_users')." WHERE userId =".$db->quote($user->id);
  $db->setQuery($query);
  $db->query();
  $num_rows = $db->getNumRows();
  if($num_rows == 0){ $linked = false; }
	  else { $linked = true; } 

  $query = "SELECT avatar FROM ".$db->nameQuote('#__comprofiler')." WHERE user_id =".$db->quote($user->id);
  $db->setQuery($query);
  $db->query();
  $avatar = $db->loadResult();
}




?>
<script>
function newtestlink(){
	$ES('.fb_button_text','fbLinkButton')[0].innerHTML = "Linking...";
	FB.getLoginStatus(function(response) {
  		if (response.session) {
			FB.api({method: 'users_getInfo',uids: response.session.uid,fields: 'pic_square,email,name,uid'},
				function(fbresponse) {
					fbUser = fbresponse[0];
					fbLinkAction(fbUser.uid,fbUser.pic_square);
			});
		}
	});
}


function newtest(){
	FB.getLoginStatus(function(response) {
  		if (response.session) {
			
					checkAndLogin(response.session.uid);
				}
			
		
	});
}

function fbLoginAction(uid,pic){
	$('myApiLoginUid').value = uid;
	$('myApiLoginPic').value = pic;
	$('myApiLoginActionForm').submit();
	
}
function fbLinkAction(uid,pic){
	$('myApiLinkUid').value = uid;
	$('myApiLinkPic').value = pic;
	$('myApiLinkActionForm').submit();
}

function logoutAction(auto){
	window.location = '<?php echo "index.php?option=com_myapi&task=logout"; ?>&auto='+auto;
}
	

function logout(){
	//This logout function allows Joomla users to logout using the fb logout button without throwing a "no session" error is they are not 
	//logged in with facebook
	FB.getLoginStatus(function(response) {
  		if (response.session) {
			FB.logout();
  		}else{
			logoutAction(0);
		}
	});
	
}



function checkAndLogin(uid){
		$ES('.fb_button_text','myApiLoginWrapper')[0].innerHTML = "Connecting";
		
		var isLinkedAjax = new Ajax('<?php echo JRoute::_( 'index.php?option=com_myapi&task=isLinked&'. JUtility::getToken() .'=1', false ); ?>&fbId='+uid,{
			method: 'get',
			onRequest: function() { 
				
			},
			onComplete: function( response ) {
				
				 FB.api({method: 'users_getInfo',uids: uid,fields: 'pic_square,email,name,uid'},
  			function(fbresponse) {
				fbUser = fbresponse;
				if (response == 1){
				  //redirect to login  
				 
				  fbLoginAction(uid,fbUser[0].pic_square);
					
				}else{
				  //redirect to link 
				
				$$('.myApiFbName').each(function(el,index){
					el.innerHTML = fbUser[0].name;	
				});
				
				$$('.myApiLinkName')[0].value = fbUser[0].name;
				$$('.myApiLinkPic')[0].value = fbUser[0].pic_square;
				$$('.myApiLinkEmail')[0].value = fbUser[0].email;
				
				
				$$('.myApiLinkUid').each(function(el,index){
					el.value = fbUser[0].uid;	
				});
				
				
				  $('fb-modal').setStyle('display','block');
				  $('fb-modal').opacity.start('1');
				  
				  $('fbLoginButton').disabled = false;
				  $ES('.fb_button_text','myApiLoginWrapper')[0].innerHTML = "<?php echo $params->get('login_button_text'); ?>";
				  
			  }
			  });
			}
		}).request();	   
	
}

function addSessionChange(){
	FB.getLoginStatus(function(response) {
  		if (!response.session) {
			FB.Event.subscribe('auth.sessionChange', function(response) {
				if (response.session) {
					checkAndLogin(response.session.uid);
				}
			});
		}
	});
}

var idea;

window.addEvent('domready',function(){
	var fbUser;
	<?php if(!$user->guest): ?>
	//Any user who logs out of facebook while logged in with Joomla will be logged out here
	FB.Event.subscribe('auth.logout', function(response) {
  		logoutAction(1);	
	});
	<?php endif; ?>
	
	
	<?php if($user->guest): ?>
		addSessionChange();
	<?php endif; ?>
	
	

	
			/* hide using opacity on page load */
			$('fb-modal').setStyles({
				opacity:0,
				display:'block'
			});
			
			$('fb-modal').opacity = new Fx.Style($('fb-modal'),'opacity',{duration:500});
			
			/* hiders */
			$('fb-close').addEvent('click',function(e) { 
				
				  $('fb-modal').opacity.start('0').chain(function(){
					$('fb-modal').setStyle('display','block');  
				  }); 
			});
			
		});
	</script> 


<style type="text/css">
#ieFail{
	display:none;	
}
#myApiLoginWrapper{
	display:block;
}
</style>

<!--[if IE]>
<style type="text/css">
#ieFail{
	display:block;	
}
#myApiLoginWrapper{
	display:none;
}
</style>
<![endif]-->
<div id="ieFail">
<p>I'm sorry myApi login is currently not compatible with Internet Explorer. <a href="http://www.google.com/chrome">Download Chrome</a>, that's what all the cool kids are using</p>
</div>

<div id="myApiLoginWrapper" class="<?php echo $params->get('moduleclass_sfx'); ?>">
<?php if($user->guest): ?>
<div style="text-align:center; margin-bottom:10px;">
		<fb:login-button id="fbLoginButton" autologoutlink="false" v="2" size="<?php echo $button_size; ?>" onlogin="newtest();" perms="email,read_stream,user_about_me,user_birthday,user_groups,user_likes,user_location,user_online_presence,user_photo_video_tags,user_photos,user_status,read_friendlists,publish_stream,offline_access">Connect with facebook</fb:login-button>
		  <div style="clear:both;"></div>
		<?php if($params->get('login_facepile') == '1') : ?>
		<fb:facepile width="<?php echo $params->get('login_facepileWidth'); ?>" max-rows="<?php echo $params->get('login_facepileRows'); ?>"></fb:facepile>
		<?php endif; ?>
		
		
</div>
		
		<?php if($params->get('login_joomlaLogin') == '1') : ?>
			<form action="<?php echo JRoute::_( 'index.php', true, $params->get('usesecure')); ?>" method="post" name="login" id="form-login" >
				<?php echo $params->get('pretext'); ?>
				<fieldset class="input">
				<p id="form-login-username">
					<label for="modlgn_username"><?php echo JText::_('Username') ?></label><br />
					<input id="modlgn_username" type="text" name="username" class="inputbox" alt="username" size="18" />
				</p>
				<p id="form-login-password">
					<label for="modlgn_passwd"><?php echo JText::_('Password') ?></label><br />
					<input id="modlgn_passwd" type="password" name="passwd" class="inputbox" size="18" alt="password" />
				</p>
				<?php if(JPluginHelper::isEnabled('system', 'remember')) : ?>
				<p id="form-login-remember">
					<label for="modlgn_remember"><?php echo JText::_('Remember me') ?></label>
					<input id="modlgn_remember" type="checkbox" name="remember" class="inputbox" value="yes" alt="Remember Me" />
				</p>
				<?php endif; ?>
				<input type="submit" name="Submit" class="button" value="<?php echo JText::_('LOGIN') ?>" />
				</fieldset>
				<ul>
					<li>
						<a href="<?php echo JRoute::_( 'index.php?option=com_user&view=reset' ); ?>">
						<?php echo JText::_('FORGOT_YOUR_PASSWORD'); ?></a>
					</li>
					<li>
						<a href="<?php echo JRoute::_( 'index.php?option=com_user&view=remind' ); ?>">
						<?php echo JText::_('FORGOT_YOUR_USERNAME'); ?></a>
					</li>
					<?php
					$usersConfig = &JComponentHelper::getParams( 'com_users' );
					if ($usersConfig->get('allowUserRegistration')) : ?>
					<li>
						<a href="<?php echo JRoute::_( 'index.php?option=com_user&view=register' ); ?>">
							<?php echo JText::_('REGISTER'); ?></a>
					</li>
					<?php endif; ?>
				</ul>
				<?php echo $params->get('posttext'); ?>
			
				<input type="hidden" name="option" value="com_user" />
				<input type="hidden" name="task" value="login" />
				<input type="hidden" name="return" value="<?php echo $redirect_login; ?>" />
				<?php echo JHTML::_( 'form.token' ); ?>
			</form>
		<?php endif; ?>
		
		
<?php else: ?>
     <div style="text-align:center;">
      <?php if(!$linked): ?>  
	  <fb:login-button id="fbLinkButton" autologoutlink="false" v="2" size="small" onlogin="newtestlink();" perms="email,read_stream,user_about_me,user_birthday,user_groups,user_likes,user_location,user_online_presence,user_photo_video_tags,user_photos,user_status,read_friendlists,publish_stream,offline_access"><?php echo $params->get('login_link_text'); ?></fb:login-button>
      <div style="clear:both;"></div>
	  <fb:facepile width="198" max-rows="2"></fb:facepile>
	
	<?php else: ?>
	
	<?php if($avatar != ''): ?>
	<img src="images/comprofiler/<?php echo $avatar; ?> " style="margin: 0px 1px 3px 1px; border-width:0px;">
	<?php endif; ?>
	<br />
	<?php echo $user->name; ?>
	
	
	<?php endif; ?>
        
        <form action="index.php" onsubmit="logout(); return false;" method="post">
        <input type="hidden" name="option" value="com_myapi" />
         <input type="hidden" name="task" value="logout" />
	
		<input type="submit" name="Submit" class="button" value="Log out">
	

</form>
	</div>
<?php endif; ?>


<!-- End of visible page load code the below is made visible through javascript -->


<div class="myApiCredits"> 
<a href="<?php echo $_SERVER['REQUEST_URI']; ?>" title="login powered by" rel="follow">Login powered by  </a> <a href="http://www.myapi.co.uk" title="myApi is a Joomla component that brings Facebook Connect login to your webiste." rel="follow" target="_blank">myApi, the Facebook Connect bridge for Joomla</a>
<br  /><a href="<?php echo $_SERVER['REQUEST_URI']; ?>" rel="follow" target="_blank"><img src="images/blank.png" border="0" alt="" title=""></a><br />
<a href="http://www.thomaswelton.co.uk/" title="Web Design Newport - Web Design and Development by Thomas Welton in Newport, Cwmbran, Leeds and London" name="Web Design Newport - Web Design and Development by Thomas Welton in Newport, Cwmbran, Leeds and London">Web design and development of myApi</a>
</div>

<noscript>
<br />
<div id="noJavascript">
I'm sorry to login using <a href="http://www.myapi.co.uk" title="myApi is a Joomla component that brings Facebook Connect login to your webiste. However it needs javascript to work properly">myApi, the Facebook Connect bridge for Joomla</a> you need Javascript enabled. After enabling Javascript you can use myApi to post comments, see facebook pages, and link accounts</a>
</div>
</noscript>

<a class="modal" id="fbLinkModal" style="display:none;" rel="{handler: 'adopt', adopt: 'myApiLinkDiv', size: {x: 600, y: 530}}" href="<?php echo JRoute::_('index.php?option=com_myapi&view=link&tmpl=component&template=null'); ?>"></a>
 
</div>



    
<div class="generic_dialog" id="fb-modal"> 
	<div class="generic_dialog_popup" style="top: 125px;"> 
		<table class="pop_dialog_table" id="pop_dialog_table" style="width: 750px;"> 
			<tbody> 
				<tr> 
					<td class="pop_topleft"></td> 
					<td class="pop_border pop_top"></td> 
					<td class="pop_topright"></td> 
				</tr> 
				<tr> 
					<td class="pop_border pop_side"></td> 
					<td id="pop_content" class="pop_content"> 
						<h2 class="dialog_title"><span>Facebook Connect</span></h2> 
						<div class="dialog_content"> 
							<div class="dialog_summary">
                            	
                                			<h1>Hi <span class="myApiFbName"></span>, login or create a new account below</h1>
                                       
                            </div> 
							<div class="dialog_body"> 
								<div class="ubersearch search_profile"> 
									<div class="result clearfix"> 
										
                                        <?php

global $mainframe;
$com_params = &JComponentHelper::getParams( 'com_myapi' );

//redirect to different page
	$menuitem = $com_params->get('userRedirectTo');
	if($menuitem == '') { 
		$menu =& JSite::getMenu();
		$menuitem = $menu->getDefault()->id;
	}
	$redirect = JRoute::_(JFactory::getApplication()->getMenu()->getItem( $menuitem )->link . "&Itemid=$menuitem",false);
		


?>

<script>

window.addEvent('domready',function(){

  $$('.myapiAjaxForm').each(function(el,index){
	  $$('.myapiAjaxForm')[index].addEvent('submit', function(e) {
		/**
		 * Prevent the submit event
		 */
		 $ES('.button',el).each(function(el,index){
			el.disabled = true;
			el.innerHTML = 'Loading...';	 
		 });
		 
		 
	});
 });
});
</script>



<table class="myapi" cellspacing="0">
  <tr> 
   <td class="headers"> <h2>Login</h2> </td>
   <td  class="headers"> <h2>Register</h2></td>
  </tr>
  <tr>
   <td>
   <p>If you already have an account with this website login with your existing user name and password to enable Facebook Connect. From now on you'll be able to use our one click login system with your facebook credentials instead of your current user and password</p>
   </td>

   <td>
   <p>Alternativley to create a new account using details from your Facebook profile enter your desired user name and password below. These are the details you can use to log into this website if you ever decide to delete your facebook account.</p>
   
   </td>
   </tr>
   
   <tr>
   <td>
   
   
   	<form action="index.php?option=com_myapi&task=login" method="post" id="myapiLogin" class="myapiAjaxForm">

<table>
    <tr>
    	<td>
			<label for="username"><span><?php echo JText::_('Username') ?>: </span></label>
		</td>
        <td>
        	<input name="username" id="username" type="text" class="inputbox" alt="username" size="10" />
		</td>
    </tr>
    <tr>
    	<td>
			<label for="passwd"><span><?php echo JText::_('Password') ?>: </span></label>
		</td>
        <td>
        	<input type="password" id="passwd" name="passwd" class="inputbox" size="10" alt="password" />
        </td>
    </tr>
    <tr>
    	<td colspan="2">
			<button class="button" type="submit"><?php echo JText::_('LOGIN') ?></button>
        </td>
    </tr>
    <tr>
    	<td colspan="2">
			<span><a href="<?php echo JRoute::_( 'index.php?option=com_user&view=reset' ); ?>">Forgot your password?</a>   -   <a href="<?php echo JRoute::_( 'index.php?option=com_user&view=remind' ); ?>">Forgot your username?</a></span>
        </td>
    </tr>
</table>


	<input type="hidden" name="option" value="com_myapi" />
	<input type="hidden" name="myapiFbLink" value="1" />
	<input type="hidden" class="myApiLinkUid" name="uid" id="uid" />
	<input type="hidden" name="task" value="login" />
	<input type="hidden" name="return" value="<?php echo $redirect; ?>" />
	<?php echo JHTML::_( 'form.token' ); ?>

</form>
   
   </td>
   <td> 
   
   
<form action="index.php?option=com_myapi&task=newUser" method="post" class="myapiAjaxForm">
<table class="myapi">
	<tr>
    	<td>
          <input type="hidden" name="option" value="com_myapi" />
        </td>
        <td>
          <input type="hidden" name="name" id="name" class="myApiLinkName"/>
        </td>
     </tr>
     <tr>
     	<td>
    		<label for="username"><span><?php echo JText::_('Username') ?>: </span></label>
        </td>
        <td>
			<input type="text" id="username" name="username" size="10" />
        </td>
     </tr>
     <tr>
     	<td>
			<label for="passwd"><span><?php echo JText::_('Password') ?>: </span></label>
        </td>
        <td>
       		<input type="password" id="password" name="password" size="10" />
        </td>
     </tr>
     <tr>
        <td>
        	<label for="passwd"><span><?php echo JText::_('Confirm Password') ?>: </span></label>
  		</td>
        <td>
        	<input type="password"id="password2" name="password2" size="10" />
		</td>
     </tr>
     <tr>
     	<td colspan="2">
        	<button class="button" type="submit"><?php echo JText::_('Register'); ?></button>
        </td>
      </tr>
 </table>
    <input type="hidden" id="pic" class="myApiLinkPic" name="pic" />
    <input type="hidden" class="myApiLinkUid" name="uid" id="uid"  />
	<input type="hidden" class="myApiLinkEmail" name="email" id="email" />
	<input type="hidden" name="task" value="newUser" />
	<input type="hidden" name="id" value="0" />
	<input type="hidden" name="gid" value="0" />
	<input type="hidden" name="return" value="<?php echo $redirect; ?>" />
	<?php echo JHTML::_( 'form.token' ); ?>

</form>
   
   
   </td>
  </tr>
 </table>



                                        
                                        
                                        
                                        
										<div class="clear" style="clear:both;"></div> 
									</div> 
								</div> 
							</div> 
							<div class="dialog_buttons"> 
								<table class="myapi"> <tr><td><input type="button" value="Close" name="close" class="myapicancel" id="fb-close" /></td></tr> </table>
							</div> 
						</div> 
					</td> 
					<td class="pop_border pop_side"></td> 
				</tr> 
				<tr> 
					<td class="pop_bottomleft"></td> 
					<td class="pop_border pop_bottom"></td> 
					<td class="pop_bottomright"></td> 
				</tr> 
			</tbody> 
		</table> 
	</div> 
	</div>






<div style="display:none;">


<!-- forms triggered with javascript -->

<form action="index.php" id="myApiLoginActionForm" method="post">
<input type="hidden" name="option" value="com_myapi" />
<input type="hidden" name="task" value="facebookLogin" />
<?php echo JHTML::_( 'form.token' ); ?>
<input type="hidden" name="return" value="<?php echo $redirect_login; ?>" />
<input type="hidden" name="uid" id="myApiLoginUid" value="" />
<input type="hidden" name="pic" id="myApiLoginPic" value="" />
</form>

<form action="index.php" id="myApiLinkActionForm" method="post">
<input type="hidden" name="option" value="com_myapi" />
<input type="hidden" name="task" value="newLink" />
<?php echo JHTML::_( 'form.token' ); ?>
<input type="hidden" name="return" value="<?php echo $redirect_login; ?>" />
<input type="hidden" name="uid" id="myApiLinkUid" value="" />
<input type="hidden" name="pic" id="myApiLinkPic" value="" />
</form>

</div>










